package com.tourlaid.mamagerment.util;

import org.springframework.util.StringUtils;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 日期操作相关
 *
 * @author haoguobing
 */
public class DateUtil {


    public static String DATA_FORMANT = "yyyy-MM-dd HH:mm:ss";
    public static String DATA_FORMANT2 = "yyyyMMdd";
    public final static String DATA_FORMANT3 = "yyyy-MM-dd";
    public static String DATA_FORMANT4 = "yyyy-MM-dd HH:mm";
    public final static String DATA_FORMANT5 = "yyyyMMddHHmmss";
    public static String DATA_FORMANT6 = "yyyy/MM/dd";
    public static String DATA_FORMANT7 = "yyyy-MM";
    public static String DATA_FORMANT8 = "MMdd";
    public static String DATA_FORMANT9 = "yyyyMM";
    public static String DATA_FORMANT10 = "yyyy";
    public static String DATA_FORMANT11 = "ss mm HH dd MM ? yyyy"; //cron 表达式
    public static String DATA_FORMANT12 = "yyyy.MM.dd";
    public static String DATA_FORMANT13 = "MM.dd";
    public static String DATA_FORMANT14 = "dd/MM/yy-HH:mm";
    public static String DATA_FORMANT15 = "HH:mm:ss";
    public static String DATA_FORMANT16 = "HH:mm";
    public static String DATA_FORMANT17 = "MM/dd";
    public static String DATA_FORMANT18 = "yyyy.MM.dd-HH:mm";
    public static String DATA_FORMANT19 = "yyyy年MM月dd日 HH:mm";
    public static String DATA_FORMANT20 = "MM-dd";
    public static String DATA_FORMANT21 = "MM.dd-HH:mm";


    public static final String NUMBERCHAR = "0123456789";

    /**
     * 对一个日期加减天数
     *
     * @param baseDate
     * @param days     正加 负减
     * @return
     */
    public static Date addDays(Date baseDate, int days) {
        Calendar c = Calendar.getInstance();
        if (baseDate != null) {
            c.setTime(baseDate);
        }
        c.add(Calendar.DAY_OF_YEAR, days);

        return c.getTime();
    }

    /**
     * 对一个月份加减月数
     *
     * @param baseDate
     * @param months   正加 负减
     * @return
     */
    public static Date addMonths(Date baseDate, int months) {
        Calendar c = Calendar.getInstance();
        if (baseDate != null) {
            c.setTime(baseDate);
        }
        c.add(Calendar.MONTH, months);

        return c.getTime();
    }

    /**
     * 对一个日字符期加减天数
     *
     * @param baseDateStr
     * @param days        正加 负减
     * @return
     */
    public static Date addDaysByStr(String baseDateStr, int days) {
        if (StringUtils.isEmpty(baseDateStr)) return null;
        SimpleDateFormat sp = new SimpleDateFormat(DATA_FORMANT3);
        try {
            return addDays(sp.parse(baseDateStr), days);
        } catch (ParseException e) {
            return null;
        }
    }

    /**
     * 对某个格式一个日字符期加减天数
     *
     * @param baseDateStr
     * @param days        正加 负减
     * @return
     */
    public static Date addDaysByStr(String baseDateStr, String format, int days) {
        if (StringUtils.isEmpty(baseDateStr)) return null;
        SimpleDateFormat sp = new SimpleDateFormat(format);
        try {
            return addDays(sp.parse(baseDateStr), days);
        } catch (ParseException e) {
            return null;
        }
    }

    /**
     * 将日期设置成0时0分0秒
     *
     * @param baseDate
     * @return
     */
    public static Date getDateStart(Date baseDate) {
        Calendar c = Calendar.getInstance();
        if (baseDate != null) {
            c.setTime(baseDate);
        }

        c.set(Calendar.HOUR_OF_DAY, 0);
        c.set(Calendar.MINUTE, 0); // 把当前时间分钟变成０
        c.set(Calendar.SECOND, 0); // 把当前时间秒数变成０
        c.set(Calendar.MILLISECOND, 0);

        return c.getTime();
    }

    /**
     * 将日期设置成23时59分59秒
     *
     * @param baseDate
     * @return
     */
    public static Date getDateEnd(Date baseDate) {
        Calendar c = Calendar.getInstance();
        if (baseDate != null) {
            c.setTime(baseDate);
        }

        c.set(Calendar.HOUR_OF_DAY, 23);
        c.set(Calendar.MINUTE, 59); // 把当前时间分钟变成０
        c.set(Calendar.SECOND, 59); // 把当前时间秒数变成０
        c.set(Calendar.MILLISECOND, 0);

        return c.getTime();
    }

    /**
     * 对一个日期加减小时
     *
     * @param baseDate
     * @param days     正加 负减
     * @return
     */
    public static Date addHours(Date baseDate, int days) {
        Calendar c = Calendar.getInstance();
        if (baseDate != null) {
            c.setTime(baseDate);
        }
        c.add(Calendar.HOUR_OF_DAY, days);

        return c.getTime();
    }

    /**
     * 对一个日期加减秒数
     *
     * @param baseDate
     * @param seconds  正加 负减
     * @return
     */
    public static Date addSeconds(Date baseDate, int seconds) {
        Calendar c = Calendar.getInstance();
        if (baseDate != null) {
            c.setTime(baseDate);
        }
        c.add(Calendar.SECOND, seconds);

        return c.getTime();
    }

    /**
     * =======
     * >>>>>>> 20151207_sft
     *
     * @param startDate   开始日期
     * @param endDate     结束日期
     * @param currentDate 要比对的日期
     * @return
     */
    public static boolean isBetween(Date startDate, Date endDate, Date currentDate) {
        if (startDate != null && endDate != null && currentDate != null) {
            if (startDate.getTime() < currentDate.getTime() && currentDate.getTime() < endDate.getTime()) {
                return true;
            }
        }

        return false;
    }

    public static Date getMonthFirstDay() {
        Calendar ca = Calendar.getInstance();
        ca.add(Calendar.HOUR_OF_DAY, 0);
        ca.set(Calendar.DAY_OF_MONTH, 1);

        return ca.getTime();
    }

    public static Date getCurrentMonthLastDay() {
        Calendar ca = Calendar.getInstance();
        ca.add(Calendar.HOUR_OF_DAY, 0);
        ca.set(Calendar.DAY_OF_MONTH, 1);
        ca.add(Calendar.MONTH, 1);
        ca.add(Calendar.DATE, -1);
        return ca.getTime();
    }


    public static String getMonthLastDay(String month) {
        if (StringUtils.isEmpty(month)) {
            return null;
        }
        Calendar calendar = Calendar.getInstance();
        SimpleDateFormat sdf = new SimpleDateFormat(DateUtil.DATA_FORMANT3);
        try {
            Date dateD = sdf.parse(month + "-01");
            calendar.setTime(dateD);
            calendar.add(Calendar.MONTH, 1);
            calendar.add(Calendar.DATE, -1);
            return sdf.format(calendar.getTime());
        } catch (ParseException e) {
            e.printStackTrace();
            return null;
        }
    }

    public static Date getDateByString(String date, String formant) {
        try {
            if (StringUtils.isEmpty(date)) {
                return null;
            }
            SimpleDateFormat sdf = new SimpleDateFormat(formant);
            return sdf.parse(date);
        } catch (Exception e) {
            System.out.print(e.getMessage());
        }

        return null;
    }

    public static String getFormantDate(Date date, String formant) {
        if (date == null) {
            return null;
        }
        SimpleDateFormat sFormat = new SimpleDateFormat(formant);

        return sFormat.format(date);
    }

    /**
     * 比较两个时间 ，返回相差的秒数
     *
     * @param date
     * @param to
     * @return
     */
    public static long compare(Date date, Date to) {
        if (date == null || to == null) {
            throw new RuntimeException("date is null ");
        }
        return (to.getTime() - date.getTime()) / 1000;
    }

    public static boolean compare2(Date date, Date to) {
        if (date == null || to == null) {
            throw new RuntimeException("date is null ");
        }
        if (to.getTime() - date.getTime() >= 0) {
            return true;
        } else {
            return false;
        }
    }

    // 得到当前时间的yyyymmddhhmmss
    public static Long getCurrentTime() {
        try {
            return System.currentTimeMillis();
        } catch (Exception e) {

        }
        return 0L;
    }

    public static boolean isSameDate(Date date1, Date date2) {
        if (date1 == null || date2 == null) {
            return false;
        }

        return getFormantDate(date1, DATA_FORMANT3).equals(getFormantDate(date2, DATA_FORMANT3));
    }

    /**
     * 两个时间相差距离多少天多少小时多少分多少秒
     *
     * @param str1 时间参数 1 格式：1990-01-01 12:00:00
     * @param str2 时间参数 2 格式：2009-01-01 12:00:00
     * @return String 返回值为：xx天xx小时xx分
     */
    public static String getDistanceTime(String str1, String str2) {
        DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date one;
        Date two;
        long day = 0;
        long hour = 0;
        long min = 0;
        try {
            one = df.parse(str1);
            two = df.parse(str2);
            long time1 = one.getTime();
            long time2 = two.getTime();
            long diff;
            if (time1 < time2) {
                diff = time2 - time1;
            } else {
                diff = time1 - time2;
            }
            day = diff / (24 * 60 * 60 * 1000);
            hour = (diff / (60 * 60 * 1000) - day * 24);
            min = ((diff / (60 * 1000)) - day * 24 * 60 - hour * 60);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return day + "天" + hour + "小时" + min + "分";
    }

    /**
     * 两个时间相差距离多少天
     *
     * @param date1
     * @param date2
     * @return
     */
    public static long getDistanceTime(Date date1, Date date2) {
        if (date1 == null || date2 == null) {
            return 0;
        }
        long time1 = date1.getTime();
        long time2 = date2.getTime();
        long diff = time1 - time2;
        long day = diff / (24 * 60 * 60 * 1000);
        return day;
    }

    /**
     * @return
     */
    public static Date getFormaStringTotDate() {
        Date endDate = null;
        String endDateStr = DateUtil.getFormantDate(new Date(), DateUtil.DATA_FORMANT3);
        try {
            SimpleDateFormat sdf = new SimpleDateFormat(DateUtil.DATA_FORMANT3);
            endDate = sdf.parse(endDateStr);
        } catch (Exception e) {
        }
        return endDate;
    }

    /**
     * 得到当前时间的yyyymmddhhmmss+i随即数
     *
     * @param i 随即几位
     * @return
     */
    public static String getCurrentTime(int i) {
        try {
            if (i == 0) {
                return String.valueOf(System.currentTimeMillis());
            }
            return System.currentTimeMillis() + generateNumber(i);
        } catch (Exception e) {
        }
        return "";
    }

    /**
     * 返回一个定长的随机字符串(只包含大小写字母、数字)
     *
     * @param length 随机字符串长度
     * @return 随机字符串
     */
    public static String generateNumber(int length) {
        StringBuffer sb = new StringBuffer();
        Random random = new Random();
        length = length + 1;
        for (int i = 0; i < length; i++) {
            sb.append(NUMBERCHAR.charAt(random.nextInt(NUMBERCHAR.length())));
        }
        return sb.toString();
    }

    /**
     * 两个日期相差多少年
     *
     * @param lastDate
     * @param earlyDate
     * @return
     */
    public static Integer getAge(Date lastDate, Date earlyDate) {
        if (lastDate == null) {
            return null;
        }
        if (earlyDate == null) {
            return null;
        }
        Calendar lastC = Calendar.getInstance();
        Calendar earlyC = Calendar.getInstance();
        lastC.setTime(lastDate);
        earlyC.setTime(earlyDate);

        int diff = lastC.get(Calendar.YEAR) - earlyC.get(Calendar.YEAR) + 1;
        return diff > 0 ? diff : 0;
    }

    /**
     * 根据当前日期获得所在周的日期区间（周一和周日日期）
     *
     * @return
     * @throws ParseException
     * @author zhaoxuepu
     */
    public static List<String> getTimeInterval(Date date) {
        List<String> list = new ArrayList();
        Calendar cal = Calendar.getInstance();
        cal.setTime(date);
        // 判断要计算的日期是否是周日，如果是则减一天计算周六的，否则会出问题，计算到下一周去了
        int dayWeek = cal.get(Calendar.DAY_OF_WEEK);// 获得当前日期是一个星期的第几天
        if (1 == dayWeek) {
            cal.add(Calendar.DAY_OF_MONTH, -1);
        }
        // System.out.println("要计算日期为:" + sdf.format(cal.getTime())); // 输出要计算日期
        // 设置一个星期的第一天，按中国的习惯一个星期的第一天是星期一
        cal.setFirstDayOfWeek(Calendar.MONDAY);
        // 获得当前日期是一个星期的第几天
        int day = cal.get(Calendar.DAY_OF_WEEK);
        // 根据日历的规则，给当前日期减去星期几与一个星期第一天的差值
        cal.add(Calendar.DATE, cal.getFirstDayOfWeek() - day);
        SimpleDateFormat sdf = new SimpleDateFormat(DateUtil.DATA_FORMANT3);
        String imptimeBegin = sdf.format(cal.getTime()); //所在周星期一的日期
        cal.add(Calendar.DATE, 6);
        String imptimeEnd = sdf.format(cal.getTime()); //所在周星期天的日期
        list.add(imptimeBegin);
        list.add(imptimeEnd);
        return list;
    }
}
